package com.example.company_project_fangyu.demo.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.company_project_fangyu.demo.utils.HttpClientUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.example.company_project_fangyu.demo.common.BasicData.*;


@Service
public class LoginSet {
    @Autowired
    private HttpClientUtils httpClientUtils;

    @SneakyThrows
    public JSON getToken() {

        JSONObject params = new JSONObject();
        params.put("username",USER_KEY);
        params.put("password",PASSWORD_KEY);

        String url = BASIC_URL + "/api/open/auth";

        //发送请求
        String res = null;
        try {
            res = httpClientUtils.doPostJson(url, params.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.parseObject(res);
    }

    /**
     * 获取token值
     * @return
     */
    public String getTokenData() {
        //获取token值
        JSON json = getToken();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = objectMapper.readTree(json.toString());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return jsonNode.path("data").path("token").asText();
    }

    /**
     * 设置请求头
     * @return
     */
    public Map<String,String> getHeaders() {
        HashMap<String,String> headers = new HashMap<>();
        headers.put("token",getTokenData());
        return headers;
    }
}
